package com.fenghongzhang.day011;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void btn(View view)  {

        String s = "{\"name\":\"小明\",\"age\":16}\n";


        //转换成一个json对象
        try {
            JSONObject jsonObject = new JSONObject(s);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");

            Toast.makeText(this, name+age, Toast.LENGTH_SHORT).show();

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void btn1(View view) {
        String cla = "[{\"name\":\"小明\",\"age\":12},{\"name\":\"小明\",\"age\":12},{\"name\":\"小明\",\"age\":12}]";
        try {
            JSONArray jsonArray = new JSONArray(cla);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.getString("name");
                Toast.makeText(this, name, Toast.LENGTH_SHORT).show();

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void btn2(View view) {
        String s = "{\"data\":[{\"name\":\"小明\",\"age\":12},{\"name\":\"小明\",\"age\":13}]}";
        //对象 -- 数组
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray data = jsonObject.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                JSONObject jsonObject1 = data.getJSONObject(i);
                int age = jsonObject1.getInt("age");
                if (age == 13){
                    Toast.makeText(this,age+"" , Toast.LENGTH_SHORT).show();
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
